package com.demo.modules.mq.common.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * 确保当消息无法被RabbitMQ队列接收时（例如，因为路由键不匹配或队列不存在），应用程序能够收到通知，并记录相关信息以便调试和监控
 *
 * @author MyPC
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class RabbitMQConfirmConfig implements ApplicationContextAware {

    private final RabbitTemplate rabbitTemplate;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
//        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            //配置回调
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                log.debug("exchange:{},message:{}, Code:{}, Text:{}, key:{}",
                        returnedMessage.getExchange(), returnedMessage.getMessage(), returnedMessage.getReplyCode(),
                        returnedMessage.getReplyText(), returnedMessage.getRoutingKey());
            }
        });
    }
}
